<template>
  <div>
    <el-steps class="approve-steps" direction="vertical" v-if="showApproveRecord">
      <!--start 已经审批的步骤 -->
      <el-step class="approve-step-item" v-for="(item, idx) in haveApproveList" :key="idx">
        <i class="timeOver stepCicle" slot="icon"></i>
        <el-row slot="title" type="flex" justify="space-between">
          <h2 class="pass">
            {{ setNodeNameLanguage(item) }}
          </h2>
          <p style="color: rgba(0, 0, 0, 0.45)">{{ item.completeTime | fmt_datetime }}</p>
        </el-row>
        <template v-if="item.operateCode">
          <!-- 非自动审批的展示 -->
          <div class="approve-step-item-desc" slot="description" v-for="(ele, index) in item.taskLogVOList" :key="index">
            <template v-if="isOpenData && ele.user && ele.user.staffId">
              <open-data type="userName" :openid="ele.user.staffId"></open-data>
            </template>
            <template v-else>
              {{ getApproversLabel(ele.user.userName) }}
            </template>

            <span :class="[item.operateCode === 6 ? 'agree' : 'refuse']">{{ item.operate }}</span>

            <base-file-item :Source="ele.attached" v-for="file in ele.attached" :key="file.id" :file="file" size="small" readonly></base-file-item>
            <p v-if="ele.approveMessage">{{ $t('task.detail.components.approveSuggestion') }}： <biz-comment-html :html="ele.approveMessage"></biz-comment-html></p>
            <div type="flex">
              <span v-if="ele.sign">
                <el-image :src="ele.sign" fit="fill" style="height: 100px"></el-image>
              </span>
            </div>
          </div> 
        </template>
      </el-step>
      <!--end 已经审批的步骤 -->
      <!--start 当前审批的步骤 -->
      <el-step class="approve-step-item" status="process" v-if="status == 1">
        <i class="signature stepCicle" slot="icon"></i>
        <el-row slot="title" type="flex" justify="space-between">
          <h2 v-if="currentApproveObj.data && currentApproveObj.data.name">{{ setNameLanguage(currentApproveObj.data) }}</h2>
        </el-row>
        <div class="approve-step-item-desc" slot="description">
          <template v-if="currentApproveObj.data && currentApproveObj.data.attribute && currentApproveObj.data.attribute.candidate">
            <span>
              {{ currentApproveObj.data.attribute.candidate | vipApproveNames }}
            </span>
          </template>
          <template v-else>
            {{ $t('task.tip.approveTip3') }}
          </template>
          <span style="color: #8c8c8c">（{{ $t('common.task.approveStatus.approve') }}）</span>
        </div>
      </el-step>
      <!--end 当前审批的步骤 -->
      <!-- start 未到审批的步骤 -->
      <el-step class="approve-step-item" v-for="item in unHaveApproveList" :key="item.id" status="wait" >
        <i class="comingSoon stepCicle" slot="icon"></i>
        <el-row slot="title" type="flex" justify="space-between" v-if="unHaveApproveList.length">
          <h2 v-if="item.data && item.data.name">{{ setNameLanguage(item.data) }}</h2>
        </el-row>
        <div class="approve-step-item-desc" slot="description">
          <template v-if="item.data && item.data.attribute && item.data.attribute.candidate">
            <span>
              {{ item.data.attribute.candidate | vipApproveNames }}
            </span>
          </template>
          <template v-else>
            {{ $t('task.tip.approveTip3') }}
          </template>
          <span style="color: #8c8c8c">（{{ $t('common.task.approveStatus.pendingApproval') }}）</span>
        </div>
      </el-step>
      <!--end 未到审批的步骤 -->
    </el-steps>
    <!-- 高级审批 -->
    <task-advanced-approve
      ref="taskAdvancedApprove"
      :vip-btn-setting="vipBtnSetting"
      :approve-button-text="approveButtonText"
      :approve-attachments="approveAttachments"
      :signatures-approve="approveData"
      :approve-info-params="approveInfoParams"
      :head="head"
      :approve="approveObjectData"
      @upload="upload"
      @submit="submit"
    >
    </task-advanced-approve>
    <!-- 高级审批 -->
  </div>
</template>
<script>
/** api */
import * as TaskApi from '@src/api/TaskApi.ts';
import { approveSubmit } from '@src/api/SparepartApprove.ts';
import { toSendVipApproveForEvent} from '@src/api/EventApi'
/** components */
import TaskAdvancedApprove from '@src/modules/task/view/components/TaskAdvancedApprove.vue';
/* enum */
import { ApproveActionLabelEnum, TaskApproversLabelEnum } from '@model/enum/LabelEnum.ts';
/* util */
import { getSortAfterNodes } from '@src/util/approve';
import { useTenantId, useRootUser } from '@hooks/useRootWindow.ts';
import {enCodeAtText, getReceivers, atTextToHtml1} from '@src/util/atText'
import { cutAtTextContent } from 'pub-bbx-utils'
import { getOssUrl } from '@src/util/assets'

const defaultAvatar = getOssUrl('/avatar.png')

export default {
  name: 'advanced-approval-process',
  components: {
    TaskAdvancedApprove,
  },
  data() {
    return {
      isOpenData: false,
      approveAttachments: [], // 高级审批附件
      haveApproveList: [], // 已经审批过的
      unHaveApproveList: [], // 未审批的
      currentApproveObj: {}, // 正在审批的
      btnType: '',
      approveInfoParams: {},
      vipJson: {}, // 高级审批的attribute 字段
      vipBtnSetting: {}, // 高级审批按钮设置
      status: '', // 流程状态 2 已完成
      approveListRelations: [], //备件办理参数
      approveInfoSparePart: {},
      approveObjectData: {}
    };
  },
  props: {
    approveId: {
      type: String,
      default: '',
    },
    approveData: {
      type: Object,
      default: () => {},
    },
    approveObject: {
      type: Object,
      default: () => {},
    },
    approveNo: { // 备件申请单号
      type: String,
      default: '',
    },
    module: {
      type: String,
      default: 'sparepart',
    },
  },
  computed: {
    approveButtonText() {
      return this.btnType === 'agree' ? i18n.t('common.base.agree') : i18n.t('common.base.refuse');
    },
    // 高级审批提交接口
    approvalMethods() {
      return {
        sparepart: approveSubmit,
        event: toSendVipApproveForEvent,
      }?.[this.module] ?? approveSubmit
    },
    // 是否显示审批日志
    showApproveRecord() {
      return this.module == 'sparepart'
    },
  },
  filters: {
    vipApproveNames(approvers) {
      return approvers.map(item => item.name).join(',');
    },
    formatApproveNames(approvers) {
      if (!approvers) return;
      return approvers.map(item => item.displayName).join(',') || i18n.t('task.tip.approveTip3');
    },
    formatSynergiesNames(synergies) {
      if (synergies) return synergies.map(item => item.displayName).join(',') || '';
      return '';
    },
  },
  mounted() {
    if (this.module == 'sparepart') {
      this.initProcess();
    }
  },
  methods: {
    /** 保存审批 */
    submit (params) {
      // 校验备注必填
      if(this.vipBtnSetting?.checkRemark && !params.approveRemark){ 
        this.$refs.taskAdvancedApprove.pending = false;
        return this.$platform.notification({ type: 'error', title: this.$t('task.tip.approveTip4')})
      } 
      // 校验附件必填
      if(this.vipBtnSetting?.checkAttached && this.approveAttachments.length === 0){ 
        this.$refs.taskAdvancedApprove.pending = false;
        return this.$platform.notification({ type: 'error', title: this.$t('task.tip.vipApproveTip')})
      } 
      // 所有的审批节点数据
      let vipApproveFlowArr = this.getNodeData()
      const { currentaskId, currentNodeName,  currentNodeTemplateId} = this.approveInfoParams

      let vipParams = {
        id: this.approveId,
        approveTaskId: currentaskId,
        button: this.btnType,
        applyMessage: params.approveRemark,
        nodeName: currentNodeName,
        nodeTemplateId: currentNodeTemplateId,
        vipApproveFlow: vipApproveFlowArr,
        attachments: this.approveAttachments,
        ...(this.btnType !=='refuse' && {approveListRelations: this.approveListRelations}), // 拒绝可不传
        approveNo:this.approveNo,
        ...params,
      }
      
      let receivers = ''
      let query = ''
      receivers = getReceivers(vipParams.approveRemark, vipParams.atUsers)
      let queryData = {
        receivers,
        tenantId: useTenantId().value,
        content: cutAtTextContent(vipParams.approveRemark),
        sendUserName: useRootUser().value?.displayName,
        bizId: this.approveInfoSparePart?.objid ?? '',
        bizNo: this.approveInfoSparePart?.objno ?? '',
      };
      query = '?';
      for (let i in queryData) {
        query += `&${i}=${queryData[i]}`;
      }
      this.vipApproveSubmit(vipParams, query)
    },
    /** 审批提交接口 */ 
    async vipApproveSubmit(vipParams, query) {
      try {
        const res = await this.approvalMethods(vipParams, query)

        if (res.success) {
          this.$platform.notification({
            type: 'success',
            title: this.$t('task.tip.approveTip5')
          })
          this.refreshTab();

          // window.location.reload(); // 刷新当前页面
        } else {
          this.$platform.alert(res.message);
          if(res.code == '8016') {
            this.refreshTab()
            return
          }
          this.$refs.taskAdvancedApprove.pending = false;
        }
      }catch (error) {
        console.log(error)
      } finally { 
        this.$refs.taskAdvancedApprove.pending = false;
      }
    },
    /** 刷新页面 */
    refreshTab() {
      let fromId = window.frameElement.getAttribute('fromid');
      this.$platform.refreshTab(fromId);
      this.$emit('update')
      this.$refs.taskAdvancedApprove.visible = false;
    },
    getNodeData() {
      return this.vipJson.cells
        .filter(item => item.shape === 'approve-node')
        .map((item) => {
          return {
            nodeTemplateId: item.id,
            nodeName: item.data.name
          }
        });
    },
    /** 高级审批按钮操作 */
    async openDialog(btnType, approveListRelations, approveInfoSparePart) {
      if (this.module == 'event') {
        this.initProcess()
      }
      try {
        this.btnType = btnType;
        this.approveListRelations = approveListRelations || [];
        this.approveInfoSparePart = approveInfoSparePart;
        // 重置
        const { approveInfo } = this.approveData || {};  
        if (this.module == 'sparepart') {
          this.approveObjectData = this.approveInfoSparePart || {}
        } else {
          this.approveObjectData = this.approveObject || {}
        }
        if (this.vipJson?.cells) {
          const { buttons } = approveInfo || {};
          this.vipBtnSetting = buttons.find(item => item.enName === btnType);
        }
        this.$refs.taskAdvancedApprove.open();


      } catch (error){
        console.log(error)
      } 
    },
    /** 处理高级审批流程数据 */
    initProcess() {
      try {
        const { approveInfo = {}, logInfo, attribute } = this.approveData || {};
        this.approveInfoParams = approveInfo;
        this.status = approveInfo.status || '';
        this.vipJson = JSON.parse(attribute);
        if (this.vipJson?.cells) {
          let filterArr = getSortAfterNodes(this.vipJson.cells);
          const { currentNodeTemplateId, buttons } = approveInfo;
          let approveArr = filterArr.filter(item => item?.shape === 'approve-node');
          // 已经审批过的，需要过滤掉taskLogVOList为空的数据
          this.haveApproveList = (logInfo || []).filter(log => log.taskLogVOList && log.taskLogVOList.length) || [];

          // 当前审批的节点
          approveArr.forEach(item => {
            this.haveApproveList.forEach(ele => {
              if (item.id === ele.nodeTemplateId) {
                ele.nameLanguage = item.data.attribute.nameLanguage || null;
              }
            });
          });



          this.currentApproveObj = approveArr.find(item => currentNodeTemplateId && currentNodeTemplateId.indexOf(item.id) >= 0) || {};

          // 并行节点可能数据为空，这时候再去logInfo里面查询
          if (!this.currentApproveObj?.id) {
            const approveObj = (logInfo || []).find(item => currentNodeTemplateId && currentNodeTemplateId.indexOf(item.nodeTemplateId) >= 0)|| {};
            this.currentApproveObj = this.vipJson.cells.find(item => item.id == approveObj.nodeTemplateId)|| {};
          }
          

          this.unHaveApproveList = [];
          let haveSelectIdList = []; // 已经审批和正在审批的id集合
          approveArr.forEach(item => {
            // 如果外面的节点id包含当前的节点id，就是指向当前审批
            if (currentNodeTemplateId && currentNodeTemplateId.indexOf(item.id) >= 0) {
              haveSelectIdList.push(item.id);
              this.currentApproveObj = item;
            } else {
              if (this.haveApproveList.length === 0) {
                // 如果没有已经审批的
                this.unHaveApproveList.push(item);
              } else {
                this.haveApproveList.forEach(ele => {
                  if (ele.nodeTemplateId === item.id) {
                    haveSelectIdList.push(item.id);
                  }
                });
              }
            }
          });

          this.unHaveApproveList = approveArr.filter(item => !haveSelectIdList.includes(item.id));
        }

      }catch(error){
        console.log(error)
      }
    },
    // 设置节点名称
    setNodeNameLanguage(item) {
      if (!item.nameLanguage) return item.nodeName;
      let laEnv = this.$i18n.locale;
      return item.nameLanguage[laEnv];
    },
    // 设置节点名称
    setNameLanguage(item) {
      if (!item.attribute.nameLanguage) return item.name;
      let laEnv = this.$i18n.locale;
      return item.attribute.nameLanguage[laEnv];
    },
    // 获取审批人
    getApproversLabel(name) {
      return TaskApproversLabelEnum[name] || name;
    },
    head(src) {
      if (!src) return defaultAvatar
      return src
    },
    upload(attachment){
      this.$set(this, 'approveAttachments', attachment)
    },
  },
};
</script>
<style lang="scss" scoped>
.approve-steps {
  padding-top: 20px;
  .approve-step-item {
    color: #000000;

    .approve-attach {
      margin-top: 6px;
    }
    h2 {
      font-size: 14px;
      color: #262626;
      &.pass span {
        color: #52c41a;
      }
    }
    &-desc {
      padding: 12px;
      background: #fafafa;
    }
  }
}
.agree {
  color: #52c41a;
}
.refuse {
  color: #f56c6c;
}
.approve-step-item-desc {
  background-color: #fff !important;
  padding: 0px !important;
  word-break: break-all;
}
.stepCicle {
  width: 11px;
  height: 11px;
  border-radius: 50%;
}
.timeOver {
  background-color: $color-primary;
}
.signature {
  background-color: #faab0c;
}
.comingSoon {
  background-color: #e4e7ed;
}
::v-deep .is-text {
  border: 0px !important;
  background-color: transparent !important;
  border-color: transparent !important;
}
::v-deep .el-step__icon {
  height: 15px !important;
}
::v-deep .el-step__head {
  position: relative;
  &::after {
    content: '';
    position: absolute;
    top: 5px;
    left: 50%;
    width: 1px; /* 虚线的宽度 */
    height: 100%;
    background: linear-gradient(to bottom, #ccc 50%, transparent 50%); /* 虚线的颜色和间隔设置 */
    background-size: 100% 10px; /* 虚线宽度为1px虚线的高度的间隔为10px*/
    transform: translateX(-50%); /* 将中点调整到元素中心 */
  }
}
::v-deep .el-step:last-child .el-step__head::after {
  content: none;
}
::v-deep .el-step__line {
  width: 0px !important;
  position: relative;
}
::v-deep .el-row {
  h2 {
    font-size: 14px;
  }
}
// element-ui
::v-deep .el-step__main {
  margin-bottom: 20px;
}
::v-deep .el-step__description {
  color: #000000;
  padding: 0;
}
::v-deep .is-justify-space-between {
  color: black;
}
.form-view-row {
  padding-top: 6px;
  padding-bottom: 6px;
}
.form-view-row-approval-results {
  align-items: flex-start;
  ::v-deep .form-view-row-content {
    overflow-y: inherit;
    overflow-x: inherit;
  }
}
.signature-img {
  width: 200px;
  height: auto;
}
</style>